package com.hanxiaozhang.threadbase1ndedition.no4lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 〈一句话功能简述〉<br>
 * 〈ReentrantLock还可以指定为公平锁〉
 * <p>
 * 公平锁，基本呈有序状态
 *
 * @author hanxinghua
 * @create 2021/11/11
 * @since 1.0.0
 */
public class No4ReentrantLockFair extends Thread {

    /**
     * 参数为true表示为公平锁，请对比输出结果
     */
    private static ReentrantLock lock = new ReentrantLock(true);

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "获得锁");
            } finally {
                lock.unlock();
            }
        }
    }


    public static void main(String[] args) {

        No4ReentrantLockFair example = new No4ReentrantLockFair();
        Thread thread1 = new Thread(example);
        Thread thread2 = new Thread(example);
        thread1.start();
        thread2.start();

    }


}
